﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyMainSite.Models;
using System.IO;

namespace MyMainSite.Controllers
{
    public class ProjectsController : Controller
    {
        //
        // GET: /Projects/

        public ActionResult Index(string name)
        {
            RichardsSiteEntities context = new RichardsSiteEntities();

            ProjectsIndexModel m = new ProjectsIndexModel(name);

            m.CurrentController = "Projects";

            if (!String.IsNullOrEmpty(name))
            {
                var project = (from p in m.Projects
                               where p.FriendlyUrl.ToLower().Trim() == name.ToLower().Trim()
                               select p).Single();

                m.BlogEntries = (from e in context.BlogEntries
                                 where e.Blog.ProjectId == project.ProjectId
                                 orderby e.DateCreated descending
                                 select e).ToList();
            }

            return View(m);
        }

        public FileContentResult Images(int? projectId)
        {
            if (projectId == null)
                return null;

            RichardsSiteEntities dc = new RichardsSiteEntities();

            var p = (from pr in dc.Projects
                     where pr.ProjectId == projectId
                     select pr).SingleOrDefault();

            if (p == null)
                return null;

            if (p.ProjectScreenShots.Count <= 0)
                return null;

            var shot1 = p.ProjectScreenShots.ToList()[0];
            byte[] data = shot1.Image.ToArray();

            return new FileContentResult(data, "image/png");
        }

		public FileContentResult DownloadBuild(int? projectBuildId)
		{
			if (projectBuildId == null)
				return null;

			RichardsSiteEntities dc = new RichardsSiteEntities();

			var b = (from pb in dc.ProjectBuilds
					 where pb.ProjectBuildId == projectBuildId.Value
					 select pb).SingleOrDefault();

			if (b == null)
				return null;

			string mimeType = "application/octet-stream";

			string ext = Path.GetExtension(b.FileName).Remove(0, 1).ToLower().Trim(); // remove the leading dot

			switch (ext)
			{
				case "zip":
					{
						mimeType = "application/zip";
						break;
					}
				case "exe":
					{
						mimeType = "application/exe";
						break;
					}
			}

			var fcr = new FileContentResult(b.Data, mimeType);
			fcr.FileDownloadName = b.FileName;

			return fcr;
		}
    }
}
